const crypto = require('crypto')
const tencentcloud = require("tencentcloud-sdk-nodejs");
const VodClient = tencentcloud.vod.v20180717.Client;
import { cosWebSite, secretId,secretKey, video_RefererKey, video_SubAppId, video_VideoTimeout } from "src/setting";
import { RedisInstance } from './redis';
import PinYin from './pinyin'
import { appendFileSync, writeFileSync } from "fs";
import { join } from "path";
import { WorkTypeEnum } from "src/entity/watchRecordIc/watchRecordIc.enum";

let pinyin = new PinYin({
  charCase: 0
});

const clientConfig = {
  credential: {
    secretId: secretId,
    secretKey: secretKey,
  },
  region: "",
  profile: {
    httpProfile: {
      endpoint: "vod.tencentcloudapi.com",
    },
  },
};
const MpsClient = tencentcloud.mps.v20190612.Client
const clientConfigMps = {
  credential: {
    secretId: secretId,
    secretKey: secretKey,
  },
  region: "",
  profile: {
    httpProfile: {
      endpoint: "mps.tencentcloudapi.com",
    },
  },
};
class utils {
  constructor(){

  }
  user_token_key = '5KdQqxSw8NC5tC8na641yjDN8s6t2KLxtWJuoA5pijthS8jnmE3'
  redis_withdrawal_key = "payconsumption:withdrawal:";
  redis_payconsumption_key = "payconsumption:wallet:";

  /**
   * 判断答案被拒绝，check = 0 手动拒绝 reject_auto_time 自动拒绝时间
   */
  judeAnswerIsReject(c){
    return c.check == 0
  }

  /**
   * 判断答案是否不是自动拒绝
   * @param c 
   * @returns 
   */
  judeNotAnswerAutoReject(c){
    return !c.reject_auto_time || new Date(c.reject_auto_time).getTime() > new Date().getTime() 
  }
  
  /**
   * 获取防盗链视频链接
   * @param currentVideo
   */
  getPlayVideoUrl(currentVideo){
    let oldurl:any = currentVideo.video_url || ''
    let https = 'https://'
    let http = 'http://'
    if(oldurl.indexOf(https) > -1){
      oldurl = oldurl.substring(oldurl.indexOf(https) + https.length)
    }else if(oldurl.indexOf(http) > -1){
      oldurl = oldurl.substring(oldurl.indexOf(http) + http.length)
    }
    oldurl = oldurl.split('/')
    oldurl = oldurl.slice(1,oldurl.length - 1)
    let endTime:string = parseInt((new Date().getTime() / 1000 + video_VideoTimeout).toString()).toString(16)
    let sign = this.md5(video_RefererKey + '/' + oldurl.join('/') + '/' + endTime)
    if(currentVideo.video_url){
      let newurl = currentVideo.video_url + '?t=' + endTime + '&sign=' + sign
      currentVideo.video_url = newurl
    }
  }


  filteremoji(str){
    var ranges = [
      '\ud83c[\udf00-\udfff]', 
      '\ud83d[\udc00-\ude4f]', 
      '\ud83d[\ude80-\udeff]'
    ];
    var emojireg = str.replace(new RegExp(ranges.join('|'), 'g'), '');
    return emojireg
  }

  utf16toEntities(str) { 
    var patt=/[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则 
    str = str.replace(patt, function(char){ 
        var H, L, code; 
        if (char.length===2) { 
            H = char.charCodeAt(0); // 取出高位 
            L = char.charCodeAt(1); // 取出低位 
            code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法 
            return "&#" + code + ";"; 
        } else { 
            return char; 
        } 
    }); 
    return str; 
  }

  /**
   * 最小公倍数
   * @param num1 
   * @param num2 
   * @returns 
   */
  LCM(num1, num2) {
    let hcf;
    for (let i = 1; i <= num1 && i <= num2; i++) {
      if( num1 % i == 0 && num2 % i == 0) {
        hcf = i;
      };
    };
    let lcm = (num1 * num2) / hcf;
    return lcm;
  }
  
  getMainWorkType(loadType){
    switch(loadType){
      case 'all':
        return WorkTypeEnum.all
        break;
      case 'video':
        return WorkTypeEnum.video
        break;
      case 'image':
        return WorkTypeEnum.image
        break;
    }
  }

  _parseChar(name) {
    if (Object.prototype.toString.call(name).slice(8, -1) !== 'String') {
      console.error("name is not string")
      return
    }
    let chars = pinyin.getFullChars(name);
    return chars[0].toUpperCase()
  }

  getSetting(wx, cloud_video, wx_public:Object) {
    //微信平台
    let setting_text = `"use strict";
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.video_SubAppId = ${cloud_video.SubAppId}
  exports.video_RefererKey = '${cloud_video.RefererKey}'
  exports.video_VideoTimeout = 1000 * 60
  //个人中心-访问管理-访问秘钥-API秘钥管理
  exports.secretId = '${cloud_video.secretId}' // 云点播id
  exports.secretKey = '${cloud_video.secretKey}'   //云点播key
  
  exports.wx_appid = '${wx.appid}'
  exports.wx_secret = '${wx.secret}'
  exports.wx_api = 'https://api.weixin.qq.com'
  exports.wx_open_api = 'https://open.weixin.qq.com'
  //子应用
  exports.video_SubAppId_List = {
    answer:${cloud_video.SubAppId_Answer}
  }
  //微信公众号
  exports.wx_public_params_list = ${JSON.stringify(wx_public)}
    `
    return setting_text
  }

  
  md5(content) {
    const md5 = crypto.createHash('md5')
    return md5.update(content).digest('hex')
  }

  /**
   * 删除腾讯云点播资源
   * @param FileId
   * @param then
   * @param catchF
   */
  deleteYunRes(FileId: string, SubAppId?: any, notBatchError?: boolean){
    const client = new VodClient(clientConfig);
    const params = {
      "FileId": FileId,
      "SubAppId": SubAppId
    };
    return new Promise((resolve,reject) => {
      client.DeleteMedia(params).then(
        (data) => {
          resolve(data)
        },
        (err) => {
          if(notBatchError){
            resolve(true)
          }else{
            reject(err)
          }
        }
      );
    })
  }

  /**
   * 查询腾讯云点播执行
   * @param client 
   * @param TaskId 
   * @param SubAppId 
   */
   DescribeTaskDetail(redis, client, TaskId: string, SubAppId, cb?: Function){
    client.DescribeTaskDetail({TaskId:TaskId, SubAppId: SubAppId}).then(async(res) => {
      if(res.Status === 'FINISH'){
        console.log(res,'res')
        let FileId = ''
        let video_id_new = ''
        let video_url_new = ''
        let video_cover = ''
        if(res.TaskType == 'PullUpload'){
          // FileId = res.PullUploadTask.FileId
          video_id_new = res.PullUploadTask.FileId
          video_url_new = res.PullUploadTask.FileUrl
          video_cover = res.PullUploadTask.MediaBasicInfo.CoverUrl
        }else{
          let ProcedureTask = res.EditMediaTask.Output
          video_id_new = ProcedureTask.FileId
          video_url_new = ProcedureTask.FileUrl
          let EditFileInfo = res.EditMediaTask.Input
          FileId = EditFileInfo.FileInfoSet?.[0]?.FileId
        }
        if(FileId && res.status !== 'FINISH'){
          let process = 0
          switch(res.status){
            case 'PROCESSING':
              process = 50
              break
          }
          await redis.set('ProcessVideo_CutVideo:' + FileId, JSON.stringify({
            process:process
          }))
        }

        cb && cb(undefined, {
          video_id:video_id_new,
          video_url: video_url_new,
          video_cover: video_cover
        })
        return
      }
      setTimeout(() => {
        this.DescribeTaskDetail(redis, client, TaskId, SubAppId, cb)
      },1000)
    }).catch(err => {
      cb && cb(err)
      // resolve(data)
    })
  }

    /**
   * 获取视频封面
   * @param url 
   * @param FieldId 
   * @returns 
   */
    GetVideoCovers(url: string, FieldId: any, redis) {
      const client = new MpsClient(clientConfigMps);
      let params = {
        InputInfo:{
          Type:"URL",
          UrlInputInfo:{
            Url: url
          }
        },
        "AiAnalysisTask":{
          "Definition": 58384,
        },
        OutputStorage:{
          Type:'COS',
          CosOutputStorage: {
            Bucket:'videocover-1315856084',
            Region: 'ap-beijing'
          }
        },
        OutputDir: FieldId + '/'
      }
      let rdsk = 'video_cover:' + FieldId
      client.ProcessMedia(params).then(
        (data) => {
          let loop = () => {
            client.DescribeTaskDetail({TaskId: data.TaskId}).then(async(res) => {
              if(res.Status === 'FINISH'){
                let ProcedureTask = res.WorkflowTask.AiAnalysisResultSet
                if(ProcedureTask?.length > 0){
                  let e = ProcedureTask[0]
                  if(e.CoverTask.Output?.CoverSet){
                    await redis.set(rdsk, JSON.stringify({create_time: new Date().getTime(), progress: 100, video_cover_list: e.CoverTask.Output.CoverSet.map(e => cosWebSite + e.CoverPath)}))
                  }else{
                    await redis.del(rdsk)
                  }
                }
              }else{
                setTimeout(() => {
                  loop()
                }, 100)
              }
            }).catch(async err => {
              await redis.del(rdsk)
            })
          }
          loop()

        },
        async (err) => {
          await redis.del(rdsk)
        }
      );
    }
  
    /**
     * 替换视频封面
     */
    ReplaceVideoCover(FileId: string, coverData: string): Promise<string>{
      const client = new VodClient(clientConfig);
      const params = {
        "FileId": FileId,
        "SubAppId": video_SubAppId,
        "CoverData": coverData
      };
      return new Promise(async (resolve,reject) => {
        console.log(params, 'ReplaceVideoCover')
        client.ModifyMediaInfo(params).then(data => {
          if(data.CoverUrl){
            resolve(data.CoverUrl)
          }else{
            reject("替换失败")
          }
        }).catch(err => {
          reject("替换失败" + err)
        })
      })
    }

  ProcessMedia(redis_editMedia, FileId: string, mediaUrl: string, cb?:Function, SubAppId?: number, notBatchError?: boolean){
    const client = new VodClient(clientConfig);
    const params = {
      "FileId": FileId,
      "SubAppId":SubAppId,
    };
    return new Promise(async (resolve,reject) => {
      if(redis_editMedia){
        await redis_editMedia.set('ProcessVideo_CutVideo:' + FileId, JSON.stringify({
          process:0
        }))
      }
      client.ProcessMedia(params).then(
        (data) => {
          resolve(data)
          this.DescribeTaskDetail(redis_editMedia, client, data.TaskId, SubAppId, cb)
        },
        (err) => {
          if(notBatchError){
            resolve(true)
          }else{
            reject(err)
          }
        }
      );
    })
  }
  /**
   * 查询腾讯云点播执行
   * @param client 
   * @param TaskId 
   * @param SubAppId 
   */
  DescribeTaskDetail_Copy(client, TaskId: string, cb?: Function){
    client.DescribeTaskDetail({TaskId:TaskId, SubAppId: video_SubAppId}).then(async(res) => {
      if(res.Status === 'FINISH'){
        console.log(res,'res')
        let video_id_new = ''
        let video_url_new = ''
        let video_cover_new = ''
        if(res.TaskType == 'PullUpload'){
          let PullUploadTask = res.PullUploadTask
          video_id_new = PullUploadTask.FileId
          video_url_new = PullUploadTask.MediaBasicInfo.MediaUrl
          video_cover_new = PullUploadTask.MediaBasicInfo.CoverUrl

          if(PullUploadTask.Status == 'FINISH'){
            cb({video_id_new, video_url_new, video_cover_new})
            return
          }
        }
      }
      setTimeout(() => {
        this.DescribeTaskDetail_Copy(client, TaskId, cb)
      },1000)
    }).catch(err => {
      cb && cb(err)
    })
  }
  copyMedia(FileId: string, mediaUrl: string, coverUrl: string, video_id: number, videoType: string){
    const client = new VodClient(clientConfig);
    const params:any = {
      "CoverUrl": coverUrl,
      "SubAppId": video_SubAppId,
      "MediaName": video_id + '_' + FileId + videoType
    };
    if(mediaUrl){
      let currentVideo = {video_url: mediaUrl}
      this.getPlayVideoUrl(currentVideo)
      params.MediaUrl = currentVideo.video_url
    }else{
      params.MediaUrl = coverUrl
    }
    if(!coverUrl){
      delete params.CoverUrl
    }
    console.log(params,'params')
    return new Promise(async (resolve,reject) => {
      client.PullUpload(params).then(
        (data) => {
          this.DescribeTaskDetail_Copy(client, data.TaskId, (result) => {
            resolve(result)
          })
        },
        (err) => {
          reject(err)
        }
      );
    })
  }
  pullMediaAndUpload(redis_editMedia, FileId: string, mediaUrl: string, coverUrl: string, cb?:Function, SubAppId?: number, notBatchError?: boolean){
    const client = new VodClient(clientConfig);
    const params = {
      "MediaUrl": mediaUrl,
      "CoverUrl": coverUrl,
      "SubAppId": SubAppId
    };
    return new Promise(async (resolve,reject) => {
      await redis_editMedia.set('ProcessVideo_CutVideo:' + FileId, JSON.stringify({
        process:0
      }))
      client.PullUpload(params).then(
        (data) => {
          resolve(data)
          this.DescribeTaskDetail(redis_editMedia, client, data.TaskId, SubAppId, cb)
        },
        (err) => {
          if(notBatchError){
            resolve(true)
          }else{
            reject(err)
          }
        }
      );
    })
  }
  /**
   * 按秒截取视频
   * @param SubAppId 
   * @param FileId 
   * @param StartTimeOffset 
   * @param EndTimeOffset 
   * @param notBatchError 
   * @returns 
   */
  editMedia(redis_editMedia, FileId: string, StartTimeOffset: number, EndTimeOffset: number, cb?:Function, SubAppId?: number, notBatchError?: boolean){
    const client = new VodClient(clientConfig);
    const params = {
      SubAppId: SubAppId,
      InputType:"File",
      FileInfos:[
        {
          FileId:FileId,
          StartTimeOffset:Number(StartTimeOffset),
          EndTimeOffset:Number(EndTimeOffset)
        }
      ]
    };
    return new Promise(async (resolve,reject) => {
      await redis_editMedia.set('ProcessVideo_CutVideo:' + FileId, JSON.stringify({
        process:0
      }))
      client.EditMedia(params).then(
        (data) => {
          resolve(data)
          this.DescribeTaskDetail(redis_editMedia, client, data.TaskId, SubAppId, cb)
        },
        (err) => {
          if(notBatchError){
            resolve(true)
          }else{
            reject(err)
          }
        }
      );
    })
  }

  DescribeMediaInfos_GetprocedureGenFile(Fields, SubAppId){
    const client = new VodClient(clientConfig);
    return new Promise(async (resolve,reject) => {
          let txt = []
          let loop = (currentFields) => {
          const params = {
            SubAppId: SubAppId,
            FileIds:currentFields,
          };
          console.log(params,'params')
          client.SearchMedia(params).then(
            (data) => {
              data.MediaInfoSet.filter(e => e.BasicInfo.Name == 'procedureGenFile').map(e => {
                txt.push('"' + e.FileId + '"')
                console.log(e.BasicInfo)
              })
              Fields.splice(0,10)
              if(Fields.length > 0){
                loop(Fields.slice(0,10))
              }else{
                appendFileSync(join(__dirname,'video.txt'),txt.join(',') + '\n')
                resolve(data)
              }
            },
            (err) => {
              console.log(err,'error')
              reject(err)
            }
          );
        }
       
        loop(Fields.slice(0,10))
        
    })
  }

  validIsNull(validValue){
    return validValue === undefined || validValue === null || validValue === ''
  }

  loadTypeToNumber(loadType){
    switch(loadType){
      case 'question':
        return 1
        break;
      case 'collection':
        return 2
        break;
      case 'original':
        return 3
        break;
      case 'answer':
        return 4
        break;
    }
  }
  
  DescribeMediaInfos(Fields, SubAppId){
    const client = new VodClient(clientConfig);
    Fields = ["243791581304076287","243791581316660401","243791581319133723","3270835010008505582","243791581324723579","243791581325523747","243791581325686287","243791581325684426","243791581326969524","243791581327371977","243791581326957725","243791581327818319","243791581328138910","243791581337297372","243791581336468792","243791581332909950","243791581336874484","243791581346561541","243791581345057694","243791581344788787","243791581337630185","243791581350141682","243791581348857747","243791581356890395","243791581357291877","243791581356763223","243791581356623233","243791581385791137","243791581378944004","243791581390477458","243791581407508808","243791581427925805","243791581480139780","243791581482346719","243791581483894697","243791581567038242","243791581557952555","243791581562506728","243791581562775284","243791581567542518","243791581567680198","243791581564100695","243791581569354539","243791581559905552","243791581677829079","243791581683863824","243791581683704356","243791581683869053","243791581684609429","243791581693020939","243791581692583294","243791581693421943","243791581693470630","243791581699293904","243791581700700362","243791581701589861","243791581701546816","243791581702436944","243791581701854311","243791581701963059","243791581703776439","243791581703342175","243791581703880771","243791581703832373","243791581713000701","243791581715158445","243791581713637063","243791581723005517","243791581722555299","243791581724905298","243791581758373604","243791581773533750","243791581776442496","243791581776581594","243791581779787092","243791581793414349","243791581793685219","243791581796513732","243791581796501297","243791581796426285","243791581797010674","243791581796408306","243791581798449311","243791581798659099","243791581814013254","243791581814502692","243791581814128457","243791581812918339","243791581814917986","243791581864529549","243791581865080594","243791581872639626","243791581871468378","243791581882241246","243791581883662263","243791581891397912","243791581932764540","243791581989462046","243791582023650386","243791582033217930","243791582040379434","243791582043995597","3270835008903661701","3270835008915713678","3270835008971825603","3270835009035459686","3270835009053775412","3270835009061691261","3270835009061531534","3270835009059678716","3270835009365554631","3270835009367482542","3270835009408937705","3270835009437899894","3270835009435495663","3270835009475684785","3270835009479144931","3270835009480157857","3270835009478891685","3270835009479561635","3270835009478834211","3270835009477349668","3270835009550807720","3270835009575053040","3270835009799587464","3270835009935589170","3270835009974023368","3270835009974073384","3270835009986883285","3270835010004872578","3270835010049285127","3270835010047640307","3270835010119741313","3270835010139167216","3270835010227219723","3270835010254763911","3270835010305658769","3270835010365218992"]
    let sql = []
    let query = []
    return new Promise(async (resolve,reject) => {
          let txt = []
          let loop = (currentFields) => {
          const params = {
            SubAppId: SubAppId,
            FileIds:currentFields,
          };
          console.log(params,'params')
          client.SearchMedia(params).then(
            (data) => {
              data.MediaInfoSet.filter(e => e.BasicInfo.Name == 'procedureGenFile').map(e => {
                console.log(e)
                sql.push(`update video set video_cover = '${e.BasicInfo.CoverUrl}' where video_id = '${e.FileId}'`)
                query.push(`select * from video where video_id = '${e.FileId}'`)
              })
              Fields.splice(0,10)
              if(Fields.length > 0){
                loop(Fields.slice(0,10))
              }else{
                appendFileSync(join(__dirname,'update.txt'),sql.join(';\n'))
                appendFileSync(join(__dirname,'select.txt'),query.join(';\n'))
                resolve(data)
              }
            },
            (err) => {
              console.log(err,'error')
              reject(err)
            }
          );
        }
       
        loop(Fields.slice(0,10))
        
    })
  }

  DescribeMediaInfos_CoverGet(Fields, SubAppId){
    const client = new VodClient(clientConfig);
    Fields = ["243791581304076287","243791581316660401","243791581319133723","3270835010008505582","243791581324723579","243791581325523747","243791581325686287","243791581325684426","243791581326969524","243791581327371977","243791581326957725","243791581327818319","243791581328138910","243791581337297372","243791581336468792","243791581332909950","243791581336874484","243791581346561541","243791581345057694","243791581344788787","243791581337630185","243791581350141682","243791581348857747","243791581356890395","243791581357291877","243791581356763223","243791581356623233","243791581385791137","243791581378944004","243791581390477458","243791581407508808","243791581427925805","243791581480139780","243791581482346719","243791581483894697","243791581567038242","243791581557952555","243791581562506728","243791581562775284","243791581567542518","243791581567680198","243791581564100695","243791581569354539","243791581559905552","243791581677829079","243791581683863824","243791581683704356","243791581683869053","243791581684609429","243791581693020939","243791581692583294","243791581693421943","243791581693470630","243791581699293904","243791581700700362","243791581701589861","243791581701546816","243791581702436944","243791581701854311","243791581701963059","243791581703776439","243791581703342175","243791581703880771","243791581703832373","243791581713000701","243791581715158445","243791581713637063","243791581723005517","243791581722555299","243791581724905298","243791581758373604","243791581773533750","243791581776442496","243791581776581594","243791581779787092","243791581793414349","243791581793685219","243791581796513732","243791581796501297","243791581796426285","243791581797010674","243791581796408306","243791581798449311","243791581798659099","243791581814013254","243791581814502692","243791581814128457","243791581812918339","243791581814917986","243791581864529549","243791581865080594","243791581872639626","243791581871468378","243791581882241246","243791581883662263","243791581891397912","243791581932764540","243791581989462046","243791582023650386","243791582033217930","243791582040379434","243791582043995597","3270835008903661701","3270835008915713678","3270835008971825603","3270835009035459686","3270835009053775412","3270835009061691261","3270835009061531534","3270835009059678716","3270835009365554631","3270835009367482542","3270835009408937705","3270835009437899894","3270835009435495663","3270835009475684785","3270835009479144931","3270835009480157857","3270835009478891685","3270835009479561635","3270835009478834211","3270835009477349668","3270835009550807720","3270835009575053040","3270835009799587464","3270835009935589170","3270835009974023368","3270835009974073384","3270835009986883285","3270835010004872578","3270835010049285127","3270835010047640307","3270835010119741313","3270835010139167216","3270835010227219723","3270835010254763911","3270835010305658769","3270835010365218992"]
    console.log(Fields,'Fields')
    return new Promise(async (resolve,reject) => {
        let txt = []
        let loop = (currentField) => {
          const params = {
            SubAppId: SubAppId,
            FileId:currentField,
            MediaProcessTask:{
              "SampleSnapshotTaskSet": [
                {
                  "Definition": 10
                }
              ]
            }
          };
          console.log(params,'params222')
          client.ProcessMedia(params).then(
            (data) => {
             console.log(data)
             Fields.splice(0,1)
             if(Fields.length > 0){
              loop(Fields[0])
             }
            },
            (err) => {
              console.log(err,'error')
              reject(err)
            }
          );
        }
        loop(Fields[0])
    })
  }

  /**
   * 获取limit
   * @param pageSize 
   * @param pageIndex 
   * @returns 
   */
  getLimit(pageSize: number, pageIndex: number){
    pageSize = Number(pageSize) || 0
    pageIndex = Number(pageIndex) || 0
    let skip: number = pageSize * pageIndex
    return {skip, take: pageSize}
  }

  
  randomName(){
    let arr = 'abcdefghkmnopqrstuvwxyzABCDEFGHKMNOPQRSTUVWXYZ'
    let codeArr = arr.split('')
    let codeCount = codeArr.length
    let name = []
    for(let i = 0; i < 8; i++){
      let tempIndex:any = Math.random() * codeCount
      let tempIndex2: any = Math.random() * (codeCount - 1)
      let temp = codeArr[parseInt(tempIndex)] ? codeArr[parseInt(tempIndex)] : codeArr[parseInt(tempIndex2)]
      name.push(temp)
    }
    return name.join('')
  }

  randomNumberID(len_number: number){
    len_number = len_number || 5;
    var $chars = '0123456789';
    var maxPos = $chars.length;
    var pwd = '';
    for (var i = 0; i < len_number; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  }

  randomStringID(len_str: number, len_number: number, str_first?: boolean){
    len_str = len_str || 1;
    len_number = len_number || 5;
    var $chars = 'ABCDEFGHJKLMNPQRSTWXYZ';
    var $chars_number = '0123456789'
    var maxPos = $chars.length;
    var maxPos_number = $chars_number.length;
    var pwd = '';
    if(str_first){
      for (var i = 0; i < len_str; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
      }
      for (var i = 0; i < len_number; i++) {
        pwd += $chars_number.charAt(Math.floor(Math.random() * maxPos_number));
      }
    }else{
      for (var i = 0; i < len_number; i++) {
        pwd += $chars_number.charAt(Math.floor(Math.random() * maxPos_number));
      }
      for (var i = 0; i < len_str; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
      }
    }
    return pwd;
  }
  
  /**
   * 生成随机字符串
   */
   randomString(len: number) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhjkmnprstwxyz2345678';
    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  }

  uuid(){
    return this.md5(this.guid() + `-${new Date().getTime()}`)
  }

  guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
      return v.toString(16);
    });
  }
  
  isJSON(txt){
    try{
      let data = JSON.parse(txt)
      return true
    }catch(err){
      return false
    }
  }

  
  Format(time, fmt) {
    //author: meizz
    var o = {
      'M+': time.getMonth() + 1, //月份
      'd+': time.getDate(), //日
      'h+': time.getHours(), //小时
      'm+': time.getMinutes(), //分
      's+': time.getSeconds(), //秒
      'q+': Math.floor((time.getMonth() + 3) / 3), //季度
      S: time.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp('(' + k + ')').test(fmt)){
        if(k === 'S'){
          fmt = fmt.replace(RegExp.$1, ('000' + o[k]).substr(('' + o[k]).length));
        }else{
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
        }
      }
    return fmt;
  };

}

export default new utils()
